﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FinanceTool.Entities;
using FinanceTool.Components.Extensions;

namespace FinanceTool.Components.Mappers
{
    public class TransactionToXyMapper
    {
        private List<Transaction> _transactions;
        private Dictionary<string, decimal> _xyValues;
        private bool _isCredit;

        public decimal TotalCredit
        {
            get;
            private set;
        }

        public decimal TotalDebet
        {
            get;
            private set;
        }

        public TransactionToXyMapper(List<Transaction> transactions, bool isCredit)
        {
            _transactions = transactions;
            _isCredit = isCredit;
            _xyValues = new Dictionary<string, decimal>();
        }

        public void MapToXyValues()
        {
            _transactions.ForEach(t =>
            {
                if (_isCredit)
                {
                    if (t.IsCredit) AddCurrentMutationToDictionary(t);
                }
                else
                {
                    if (!t.IsCredit) AddCurrentMutationToDictionary(t);
                }
            });

            decimal creditValue = 0;
            decimal debetValue = 0;
            _transactions.ForEach(t =>
            {
                if (t.IsCredit) creditValue += t.Amount;
                else debetValue += t.Amount;
            });

            TotalCredit = creditValue;
            TotalDebet = debetValue;
        }

        private void AddCurrentMutationToDictionary(Transaction t)
        {
            if(_xyValues.ContainsKey(t.MutationType))
            {
                // we have already this mutationtype
                decimal curentValue = _xyValues[t.MutationType];
                _xyValues[t.MutationType] = curentValue + t.Amount;
            }
            else
            {
                _xyValues.Add(t.MutationType, t.Amount);
            }
        }

        public decimal[] ValuesY
        {
            get
            {
                return _xyValues.Values.ToArray<decimal>();
            }
        }

        public string[] ValuesX
        {
            get
            {
                return _xyValues.Keys.ToArray<string>();
            }
        }

        public decimal[] DebetCreditValuesY
        {
            get
            {
                return new decimal[] { TotalCredit, TotalDebet };
            }
        }

        public string[] DebetCreditValuesX
        {
            get
            {
                return new string[] { "Bij", "Af" };
            }
        }
    }
}
